package com.etheart.lyric.htmlparser.action.parse;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.htmlparser.Parser;
import org.htmlparser.util.ParserException;

import com.etheart.lyric.htmlparser.service.baidu.BaiduAlbumListParseService;
import com.etheart.lyric.htmlparser.service.baidu.BaiduAlbumParseService;
import com.etheart.lyric.htmlparser.service.baidu.BaiduSingerMapParserService;
import com.etheart.lyric.htmlparser.service.baidu.BaiduSingerParseService;
import com.etheart.lyric.htmlparser.util.HtmlparserUtils;
import com.etheart.model.entity.Album;
import com.etheart.model.entity.Singer;
import com.etheart.model.entity.Song;
import com.etheart.music.service.AlbumService;
import com.etheart.music.service.SingerService;
import com.etheart.music.service.SongService;

public class JujingParseThread extends Thread {
	private static final Log logger = LogFactory.getLog(JujingParseThread.class);
	private BaiduSingerParseService singerParseService;
	private BaiduAlbumParseService albumParseService;
	private BaiduAlbumListParseService albumListParseService;
	private SingerService singerService;
	private AlbumService albumService;
	private SongService songService;
	private File singersDir;  
	public boolean isStart = false;
	private String localDir;
	private String jujing = "www.top100.cn";
	public String songNetId = null;
	public String singerNetId = null;
	public String albumNetId = null;

	public static Map<String, String[]> sexMap =null;

	// 开始 和 继续的初始化方法
	public JujingParseThread(SingerService singerService, AlbumService albumService,
			SongService songService, File dir,String localDir) {
		if (sexMap==null) {
			BaiduSingerMapParserService mapService= new BaiduSingerMapParserService(localDir+"\\www.top100.cn\\artist");
			sexMap = mapService.getSingerMap();
		}
		if (isStart) {
			return;
		}
		isStart = true;
		this.singerParseService = new BaiduSingerParseService();
		this.albumParseService = new BaiduAlbumParseService();
		this.albumListParseService = new BaiduAlbumListParseService();
		this.singerService = singerService;
		this.songService = songService;
		this.albumService = albumService;
		this.singersDir = dir;
		this.localDir=localDir;
	}

	

	public boolean foundSingerBreak = false;
	public boolean foundAlbumBreak = false;
	public boolean foundSongBreak = false;
	public boolean isMatchSingerSong = false;
	
	@Override
	public synchronized void start() {
		if (StringUtils.isBlank(singerNetId)) {
			foundSingerBreak = true;
		}
		if (StringUtils.isBlank(albumNetId )) {
			foundAlbumBreak = true;
		}
		if (StringUtils.isBlank(songNetId)) {
			foundSongBreak = true;
		}
		/*
		// 判断 断点是否正确
		if (singerNetId != null) {
			Singer singer = singerService.findByNetId(singerNetId);
			if (singer != null) {
				throw new HtmlparseRuntimeException(
						"该album已存在，album断点id不正确，请填写出错的歌手netid或者最后一个添加进去的歌手的后一位歌手的netid");
			}
		}
		if (albumNetId != null) {
			Album album = albumService.findByNetId(albumNetId);
			if (album != null) {
				throw new HtmlparseRuntimeException(
						"该album已存在，album断点id不正确，请填写出错的专辑的netid 或者 数据库中最后的专辑的后一个专辑的netid");
			}
		}

		if (singerNetId == null && albumNetId == null && songNetId ==null) {
			// 如果是重新开始，则要判断数据库为空
			long singerNum = singerService.getSingerCount();
			if (singerNum > 0) {
				throw new HtmlparseRuntimeException("数据库singer表不为空，无法重新开始");
			}
		}
		*/
		super.start();
	}

	public void run() {
		FilenameFilter filter = new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) { 
				if (name.indexOf("info-")!=-1) {
					return true;
				}
				return false;
			}
		};
		
		
		File[] files = singersDir.listFiles(filter);
		for (File file : files) {
			if (!foundSingerBreak) {
				if (file.getName().indexOf(singerNetId)!=-1) {
					foundSingerBreak=true;
				}else {
					continue;
				}
			}
			
			saveSinger(file);
		}
		
	}

	private void saveSinger(File file) {
		Parser parser = HtmlparserUtils.getParser(file.getAbsolutePath(), "http://"+jujing+"/artist/"+file.getName());
		if (parser==null) {
			logger.error("singerFileGetErr:"+file.getName());
			return;
		}
	
			Singer singer = singerParseService.getSingerFromParser(parser, file.getName());
			StaticState.cur_singer = file.getAbsolutePath();
			singer.setSex(sexMap.get(singer.getNetId())[0]);
			singer.setArea(sexMap.get(singer.getNetId())[1]);
			if (singer!=null&&singer.getNetId()!=null&&singer.getNetId()!="") {
				if (singerService.findByNetId(singer.getNetId())==null) {
					singerService.addSinger(singer);
				}else{
					singer = singerService.findByNetId(singer.getNetId());
				}
			}else{
				return;
			}
			String albumUrl = "http://"+jujing+singerParseService.getAlbumListUrl(singer);
			String albumFileName = localDir+"/"+jujing+"/"+singerParseService.getAlbumListFileName(singer);
			StaticState.cur_albume = albumFileName;
			saveAlbums(albumUrl,albumFileName,singer);
		
	}

	private void saveAlbums(String albumListUrl, String albumListFileName, Singer singer) {
		String localFilePath = localDir+"/"+jujing+"/album/"+albumListFileName;
		Parser parser = HtmlparserUtils.getParser(localFilePath, albumListUrl);
		if (parser == null) {
			logger.error("albumListParserGetErr:"+albumListUrl);
			return ;
		}
		try {
			List<String> albums = albumListParseService.parseAlbumListPage(parser, localFilePath, albumListUrl);
			for (String a : albums) {
				saveAlbum(a, singer);
			}
		} catch (ParserException e) {
			logger.error("albumListParseErr:"+albumListFileName+";");
		}
	}

	private void saveAlbum(String albumUrl, Singer singer) {
		if (!foundAlbumBreak) {
			if (albumUrl.indexOf(albumNetId)!=-1) {
				foundAlbumBreak = true;
				singer = singerService.findByNetId(singer.getNetId());
			}else {
				return;
			}
		}
		String localFilePath = localDir+"/"+jujing+albumUrl;
		albumUrl = "http://"+jujing+albumUrl;
		Parser parser = HtmlparserUtils.getParser(localFilePath, albumUrl);
		if (parser == null) {
			logger.error("albumParserGetErr:"+albumUrl);
			return ;
		}
		Album album = albumParseService.getAlbum(parser, albumUrl);
		album.setSinger(singer);
		if (album!=null && album.getNetId()!=null&&album.getNetId()!="") {
			if (albumService.findByNetId(album.getNetId())==null) {
				albumService.addAlbum(album);
			}else{
				album = albumService.findByNetId(album.getNetId());
			}
		}else{
			return;
		}
		
		List<Song> songs;
		try {
			songs = albumParseService.getSongs(parser);
			for (Song song : songs) {
				if (!foundSongBreak) {
					if (song.getNetId().indexOf(songNetId)!=-1) {
						foundSongBreak = true;
						album = albumService.findByNetId(album.getNetId());
					}else {
						continue;
					}
				}
				
				song.setSinger(singer);
				song.setAlbum(album);
				if (song!=null && song.getNetId()!=null&&song.getNetId()!="") {
					if (songService.findByNetId(song.getNetId())==null) {
						songService.addSong(song);
					}
				}else{
					return;
				}
				
			}
		} catch (ParserException e) {
			logger.error("songParseErr:"+albumUrl+";");
		}
		
		
	}

	

}
